#!/usr/bin/env python
# -*- coding:utf-8 -*-
import argparse
import logging
import multiprocessing
import os

import const

__all__ = ['ParserAction', 'init_logger', 'user_agents']


class ParserAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)
        if len(values) == 0:
            setattr(namespace, 'mode', 'run')
        else:
            setattr(namespace, 'mode', 'parser')


def init_logger(name, sub_name='default', workspace=const.PATH, multiproc=False, stream=True, debug=False):
    if not os.path.exists(workspace):
        os.makedirs(workspace)

    if multiproc:
        log = multiprocessing.get_logger()
    else:
        log = logging.getLogger(name)

    log.setLevel(logging.DEBUG)
    fmt = logging.Formatter(r'[%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s')

    if stream or debug:
        sh = logging.StreamHandler()
        sh.setFormatter(fmt)
        if debug:
            sh.setLevel(logging.DEBUG)
        else:
            sh.setLevel(logging.INFO)
        log.addHandler(sh)
    else:
        sh = None

    if not debug:
        fh = logging.FileHandler(os.path.join(workspace, sub_name))
        fh.setFormatter(fmt)
        fh.setLevel(logging.INFO)
        log.addHandler(fh)
    else:
        fh = None

    return log, sh, fh
